#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@author: xiaodun
@date: 2025/8/3119:12
"""

# from requests import Session
# import pytest
# from responses_validator import validator
# from yaml_unit import yaml_unit
# import allure
# import os
#
# def create_yaml_test(yaml_file_path):
#     try:
#         data=yaml_unit(yaml_file_path)
#         base_url=yaml_unit(r"F:\PycharmProjects\commons\data_base.yaml")[0]["base_url"]
#         sess=Session()
#         # file_name = os.path.basename(yaml_file_path).replace('.yaml', '').replace('.yml', '')
#         # func_name = f"test_{file_name}"
#
#         def create_test():
#
#             @pytest.mark.parametrize("_data",data)
#             def internal_test_func(_data):
#                 name=_data['name']
#                 requests=_data['request'].copy()
#                 requests['url']=base_url+requests['url']
#                 response=_data['response']
#                 allure.dynamic.title(name)
#                 with allure.step("发送请求"):
#                     resp=sess.request(**requests)
#                 with allure.step("验证响应"):
#                     validator(resp,**response)
#             return internal_test_func
#         test_func=create_test()
#         file_name = os.path.basename(yaml_file_path).replace('.yaml', '').replace('.yml', '')
#         test_func.__name__ = f"test_{file_name}"
#
#         return test_func
#
#     except Exception as e:
#         print(f"创建函数时出错：{e}")
#         return None
# commons/create_yaml_test.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-

from requests import Session
import pytest
from responses_validator import validator
from untils.yaml_unit import yaml_unit
import allure
import os


def create_yaml_test(yaml_file_path):
    """
    根据YAML文件创建测试函数
    :param yaml_file_path: YAML测试用例文件路径
    :return: 测试函数
    """
    try:
        # 读取测试数据
        test_cases = yaml_unit(yaml_file_path)
        if not test_cases:
            print(f"警告: {yaml_file_path} 中没有测试用例")
            return None

        # 读取基础URL配置
        base_config = yaml_unit(os.path.join(os.path.dirname(__file__), "data_base.yaml"))
        base_url = base_config[0]["base_url"]

        # 创建会话
        session = Session()

        # 生成测试函数名
        file_name = os.path.basename(yaml_file_path).split('.')[0]
        func_name = f"test_{file_name}"

        # 定义测试函数
        @pytest.mark.parametrize("_case", test_cases,
                                 ids=[f"{file_name}_{i + 1}_{_case['name'][:20]}" for i, _case in
                                      enumerate(test_cases)])
        def test_func(_case):
            # 准备请求数据
            request_data = _case['request'].copy()
            request_data['url'] = f"{base_url}{request_data['url']}"

            # 设置测试标题
            allure.dynamic.title(_case['name'])

            # 发送请求
            with allure.step(f"发送请求: {request_data['method']} {request_data['url']}"):
                response = session.request(**request_data)

            # 验证响应
            with allure.step("验证响应结果"):
                validator(response, **_case['response'])

        # 设置函数名
        test_func.__name__ = func_name
        return test_func

    except Exception as e:
        print(f"创建测试函数失败 {yaml_file_path}: {str(e)}")
        return None
